#-*- coding:utf-8 -*-
import json

import urllib2
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

#定义URL账户密码
url = 'http://172.16.102.19/api_jsonrpc.php'
username = 'admin'
password = 'password'

#定义mysql的信息
cmdbip     ='172.16.102.16'
cmdbport   = 3306
cmdbname   = 'ly'
cmdbpasswd = 't8HPW6^8sg'
cmdbuser   ='root'

VMTABLE    ='gsys_admin_vm'
ROLETABLE  ='gsys_admin_role'
GAMETABLE  ='gsys_admin_db'
PORTTABLE  ='gsys_admin_port'
DB_CONNECT_STRING = r'mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8' % (cmdbuser,cmdbpasswd,cmdbip,cmdbport,cmdbname,)
# print DB_CONNECT_STRING
engine = create_engine(DB_CONNECT_STRING, echo=False)
DB_Session = sessionmaker(bind=engine)
session = DB_Session()
def get_allip():
    sql='select distinct av_vmip from gsys_admin_vm;'
    res=session.execute(sql).fetchall()
    return res
def get_hostname(ip):
    sql="select ar_role from gsys_admin_role where ar_vmid=(select sysid from gsys_admin_vm where av_vmip='%s');" % (ip)
    # sql="select sysid from gsys_admin_vm where av_vmip='%s';" % (ip)
    ress = session.execute(sql).fetchall()
    res=''
    for i in ress:
        res +=i[0]
    return res


#通过api接口获取所有的主机IP
def ipgetHostsid(ip,url,auth):
    values = {'jsonrpc': '2.0',
              'method': 'host.get',
              'params': {
                  'output': [ "host" ],
                  'filter': {
                      'ip': ip
                  }
              },
              'auth': auth,
              'id': '3'
              }
    output = requestJson(url,values)
    return output

#通过api接口更新主机的hsotname
def updatehostname(hostid,hostname,url,auth):
    values = {'jsonrpc': '2.0',
              'method': 'host.update',
              'params': {
                  "hostid": hostid,
                    "name": hostname,
              },
              'auth': auth,
              'id': '4'
              }
    output = requestJson(url, values)
    # return output

#定义通过HTTP方式访问API地址的函数，后面每次请求API的各个方法都会调用这个函数
def requestJson(url,values):
    data = json.dumps(values)
    req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
    response = urllib2.urlopen(req, data)
    output = json.loads(response.read())
#    print output
    try:
        message = output['result']
    except:
        message = output['error']['data']
        print message
        quit()

    return output['result']

#API接口认证的函数，登录成功会返回一个Token
def authenticate(url, username, password):
    values = {'jsonrpc': '2.0',
              'method': 'user.login',
              'params': {
                  'user': 'Admin',
                  'password': 'zabbix'
              },
              'id': '1'
              }
    idvalue = requestJson(url,values)
    return idvalue
allip=get_allip()
auth=authenticate(url,username,password)
#测试代码
# ip='172.16.102.22'
# hostid=hostid=ipgetHostsid(ip,url,auth)
# print hostid

for fiteip in allip:
    ip=fiteip[0]
    hostgetid = ipgetHostsid(ip, url, auth)
    if hostgetid:
        hostname = get_hostname(ip)
        for i in hostgetid:
            hostid = i['hostid']
        updatehostname(hostid,hostname,url,auth)